package cn.jdy.djgaj.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.authority.entity.User;
import cn.jdy.authority.service.UserService;
import cn.jdy.common.constant.GlobalConstant;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.djgaj.entity.DjgajNews;
import cn.jdy.djgaj.sevice.DjgajNewsService;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.safe.SafeUtil;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.framework.util.ValidationUtil;
import cn.jdy.platform.entity.ConfValue;
import cn.jdy.platform.entity.News;
import cn.jdy.platform.service.ConfService;
import cn.jdy.plugins.entity.Member;
import cn.jdy.xzgaj.entity.XzgajNews;

/**
 * @dedsc  新闻控制类
 * @author ningqian	
 * @date   2016-10-26
 */
@Controller
@RequestMapping("/djgajnews")
public class DjgajNewsCtrl extends BaseCtrl {
	@Autowired
	private DjgajNewsService newsService;
	@Autowired
	private ConfService confService;
	@Autowired
	private UserService userService;

	/**
	 * 查询新闻列表
	 * 
	 * @param news
	 * @return
	 */
	@RequestMapping("/{typeid}.html")
	public ModelAndView query(DjgajNews news, @PathVariable Long typeid) {
		ModelAndView mv = new ModelAndView("/news/newsList.jsp");
		try {
			//襄阳市公安局，需要加入当前时间段周数
			Date datetime = new Date();
			int weekdays = datetime.getDay();
			mv.addObject("weekdays",weekdays);
			
			// 设置分页信息
			if (news.getiDisplayLength() == 0)
				news.setiDisplayLength(12); // 默认长度24
			if (news.getPageNo() <= 0)
				news.setPageNo(1); // 默认页数1
			news.setiDisplayStart((news.getPageNo() - 1)
					* news.getiDisplayLength()); // 显示起始索引
			news.setStatus("1");// 状态 0：无效，1：有效
			// 当关键字不为null并且不为空时，通过关键字全分类模糊查询
			// 反之，查询当前分页状态下的信息
			if (news.getKeyword() != null && !news.getKeyword().trim().isEmpty()) {
				mv.addObject("dataList",newsService.queryByLike(news, news.getKeyword()));
				mv.addObject("total", newsService.queryByLikeCount(news, news.getKeyword()));
			} else {
				news.setColumnId(typeid);// 新闻分类

				List<DjgajNews> dataList= newsService.query(news);
				mv.addObject("total", newsService.count(news));
				
				/*** 统计还要多少要签收  开始 */
				for(DjgajNews x : dataList){
					List<String> realAssos = new ArrayList<String>();
					List<String> notAssos = new ArrayList<String>();
					String status = x.getSignStatus();
					int tempIndex=0;
					String[] zhiduis = null;
					String[] assos = null;
					if(null != x.getSignDepartment() && !"".equals(x.getSignDepartment())){
						assos = x.getSignDepartment().split(";");
					}
					int len = 0,cnt=0;
					//公安-签收状态有别于特警，直接加入签收用户名，用,逗号分隔
					if(status!=null && status!=""){
						zhiduis = status.split(",");//已签收单位String数组
					}
					
					if(null != assos){
						for(int i=0;i<assos.length;i++){
							if((assos[i]!=null)){
								realAssos.add(cnt, assos[i]);
								//未签收
								if(zhiduis!=null && zhiduis.length>0){
									int tempCnt=0;
									for(int it=0;it<zhiduis.length;it++){
										if(!(assos[i].equals(zhiduis[it]))){
											tempCnt++;
										}
									}
									if(tempCnt==zhiduis.length){
										notAssos.add(tempIndex, assos[i]);
										tempIndex++;
									}
								}else{
									notAssos.add(cnt, assos[i]);
								}
								cnt++;
							}
						}
					}
					 if(realAssos.size()>0){
						 x.setSignStatus(notAssos.size()+"");//用这个字段迭代到前台			
						}else{
							x.setSignStatus("-1");
						}
					
				}
				/***  统计还要多少要签收  结束*/
				mv.addObject("dataList", dataList);
			}
			
			mv.addObject("pageNo", news.getPageNo());
			mv.addObject("size", news.getiDisplayLength());
			ConfValue cv = confService.find(typeid); // 获取分类的父id,查询同级分类
			mv.addObject("typeName", cv.getValue0());// 分类的名称 用于 页面导航路径展示
			news.setCv(cv);
			if (0 == cv.getPid()) {
				mv.addObject("newsClass", null);// 根据大分类 查询小分类 列表
			} else {
				List<ConfValue> plist = confService.queryByType(
						GlobalConstant.TYPE_NEWS, cv.getPid());// 新闻分类
				mv.addObject("newsClass", plist);// 根据大分类 查询小分类 列表
				// ConfValue pcv = confService.find(cv.getPid()); // 查询父分类名称
				// mv.addObject("typeName", pcv.getValue0());// 父分类的名称 用于
				// 页面导航路径展示
			}
			mv.addObject("news", news);
			mv.addObject("typeid", typeid);
			mv.addObject("key", news.getKeyword()); 
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询文章异常", e);
		}
		return mv;
	}

	/**
	 * 新闻详细内容页
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/show-{id}.html")
	public ModelAndView queryDetail(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView("/news/newsDetail.jsp");
		
		//襄阳市公安局，需要加入当前时间段周数
		Date datetime = new Date();
		int weekdays = datetime.getDay();
		mv.addObject("weekdays",weekdays);
		
		try {
			DjgajNews news = newsService.find(id);
			if (0 == news.getCv().getPid()) {
				mv.addObject("newsClass", null);// 根据大分类 查询小分类 列表
			} else {
				List<ConfValue> plist = confService.queryByType(
						GlobalConstant.TYPE_NEWS, news.getCv().getPid());// 新闻分类
				mv.addObject("newsClass", plist);// 根据大分类 查询小分类 列表
				ConfValue cv = confService.find(news.getColumnId()); // 获取分类的父id,查询同级分类
				mv.addObject("typeName", cv.getValue0());// 分类的名称 用于 页面导航路径展示
			}
			mv.addObject("news", news);
			// 增加一次查看
			if (news != null) {
				news.setReadTimes(news.getReadTimes() == null ? 1 : news
						.getReadTimes() + 1);
				newsService.update(news);
			}
			
			String status = news.getSignStatus();
			String[] zhiduis = null;
			String[] assos = null;
			if(null != news.getSignDepartment() && !"".equals(news.getSignDepartment())){
				assos = news.getSignDepartment().split(";");
			}
			List<String> realAssos = new ArrayList<String>();
			List<String> notAssos = new ArrayList<String>();
			int len = 0,cnt=0;
			//公安-签收状态有别于特警，直接加入签收用户名，用,逗号分隔
			if(status!=null && status!=""){
				zhiduis = status.split(",");//已签收单位String数组
			}
			int tempIndex=0;
			if(null != assos){
				for(int i=0;i<assos.length;i++){
					if((assos[i]!=null)){
						realAssos.add(cnt, assos[i]);
						//未签收
						if(zhiduis!=null && zhiduis.length>0){
							int tempCnt=0;
							for(int it=0;it<zhiduis.length;it++){
								if(!(assos[i].equals(zhiduis[it]))){
									tempCnt++;
								}
							}
							if(tempCnt==zhiduis.length){
								notAssos.add(tempIndex, assos[i]);
								tempIndex++;
							}
						}else{
							notAssos.add(cnt, assos[i]);
						}
						cnt++;
					}
				}
			}
			
			mv.addObject("realAssos", realAssos);//需要签收的单位gaj
			mv.addObject("signAssos", zhiduis);//已签收的支队名称 gaj
			mv.addObject("notAssos", notAssos);//未签收的支队名称 gaj
			mv.addObject("id", id);//未签收的支队名称 gaj
			// 获得系统所有签收单位
			List<ConfValue> list = confService.queryByType(72,null);
			mv.addObject("deptList", list);
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "新闻详细内容页异常", e);
		}
		return mv;
	}
	
	/**
	   * 签收登陆
	   */
	  @RequestMapping("/login/{id}")
	  public ModelAndView loginMores(@PathVariable Long id) {
	    ModelAndView mv = new ModelAndView("/news/login.jsp");
	  //襄阳市公安局，需要加入当前时间段周数
		Date datetime = new Date();
		int weekdays = datetime.getDay();
		mv.addObject("weekdays",weekdays);
	  		
		mv.addObject("id", id);
	    return mv;
	  }
	  
	  /**
		 * 东津公安局
		 * 先验证登陆信息；通过后签收
		 * 签收通知通报：多个用户均需要签收
		 * @param id
		 * @param name 登录用户名 String
		 * @return
		 */
		@RequestMapping("/signes/{id}")
		public ModelAndView signeds(@PathVariable Long id, String username,String password) {
			ModelAndView mv = new ModelAndView("redirect:/djgajnews/show-"+id+".html");
			
			/*校验输入信息是否合法*/
			String str = "";//提示信息
			if(ValidationUtil.isEmpty(username)) {
				str = "请输入用户名";// 请输入用户名或手机号
			} else if(ValidationUtil.isEmpty(password)) {
				str = "请输入密码";// 请输入密码
			}
			if("".equals(str)) {
				User member = userService.findMemberByUsername(username);
				if(null != member) {
					if(SafeUtil.md5(password).substring(8, 16).equals(member.getPasswd())) {
						//登陆成功-则进行点击登录进行签收
						DjgajNews data = this.newsService.find(id);
						
						String[] assos = null;
						if(null != data.getSignDepartment() && !"".equals(data.getSignDepartment())){
							assos = data.getSignDepartment().split(";");
						}
						if(null != assos){
							int lens = assos.length;
							String statuses = data.getSignStatus();
							if(statuses==null){
								for(int iter=0;iter<lens;iter++){
									if(assos[iter]!=null && assos[iter].equals(username)){
										data.setSignStatus(username);//将状态1换成用户名
									}
								}
							}else{
								for(int iter=0;iter<lens;iter++){
									//同一账户重复签收无影响 如果先签收jwbzb,接着签收jw此法出错
//								if(assos[iter]!=null && statuses.indexOf(username)==-1 && assos[iter].equals(username)){
									if(assos[iter]!=null && assos[iter].equals(username)){
										if (username.equals("jjzd")) {
											if(statuses.indexOf("gsjjzd")!=-1){//如果有
												if(statuses.indexOf("jjzd", statuses.indexOf("gsjjzd")+6) ==-1){//随后没有jw
													data.setSignStatus(statuses+","+username);
												}
											}else{
												data.setSignStatus(statuses+","+username);
											}
										} else{
											if(statuses.indexOf(username)==-1)
												data.setSignStatus(statuses+","+username);
										}
									}
								}
							}
							this.newsService.update(data);
						}
					}else{
						//登陆失败
						str="登录失败";
					}
				}
			}
			
			return mv;
		}
	

	/**
	 * 查询新闻列表
	 * 
	 * @param news
	 * @return
	 */
	@RequestMapping("/myNews")
	public ModelAndView myNews(DjgajNews news) {
		ModelAndView mv = new ModelAndView("/my/myNewsInfo.jsp");
		try {
			Member mbo = (Member) session.getAttribute("user");
			if (mbo == null) {
				mv.setViewName("404.jsp");
			} else {
				news.setUserid(mbo.getId());
				// 设置分页信息
				if (news.getiDisplayLength() == 0)
					news.setiDisplayLength(10); // 默认长度5
				if (news.getPageNo() <= 0)
					news.setPageNo(1); // 默认页数1
				news.setiDisplayStart((news.getPageNo() - 1)
						* news.getiDisplayLength()); // 显示起始索引
				mv.addObject("dataList", newsService.query(news));
				mv.addObject("pageNo", news.getPageNo());
				mv.addObject("size", news.getiDisplayLength());
				mv.addObject("total", newsService.count(news));
				mv.addObject("news", news);
			}
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询文章异常", e);
		}
		return mv;
	}

	/**
	 * 删除新闻
	 * 
	 * @param news
	 * @return
	 */
	@RequestMapping("/delNews")
	public ModelAndView delNews(News news, Long id) {
		ModelAndView mv = new ModelAndView("redirect:/DjgajNews/myNews");
		try {
			Member mbo = (Member) session.getAttribute("user");
			if (mbo == null) {
				mv.setViewName("404.jsp");
			} else {
				newsService.delete(id);
			}
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询文章异常", e);
		}
		return mv;
	}

	/**
	 * 初始化新闻
	 * 
	 * @param news
	 * @return
	 */
	@RequestMapping("/initNews")
	public ModelAndView initNews(DjgajNews news, Long id) {
		ModelAndView mv = new ModelAndView("/my/newsDetail.jsp");
		mv.addObject("column",
				this.confService.queryByType(GlobalConstant.TYPE_NEWS, 9667L));
		Member mbo = (Member) session.getAttribute("user");
		if (mbo == null) {
			mv.setViewName("404.jsp");
		} else {
			news = newsService.find(id);
			mv.addObject("data", news);
		}
		return mv;
	}

	/**
	 * 保存新闻
	 * 
	 * @param news
	 * @return
	 */

	@RequestMapping("/saveNews")
	public ModelAndView saveNews(DjgajNews news) {
		ModelAndView mv = new ModelAndView("redirect:/DjgajNews/myNews");
		Member mbo = (Member) session.getAttribute("user");
		if (mbo == null) {
			mv.setViewName("404.jsp");
		} else {
			news.setUserid(mbo.getId());
			news.setCreateTime(DateUtil.getCurrentDate2());
			newsService.saveOrUpdate(news);
		}
		return mv;
	}
	
	/**
	 * 值班
	 * @param news
	 * @return
	 */
	@RequestMapping("/onDuty")
	public ModelAndView onDuty(News news) {
		ModelAndView mv = new ModelAndView("/news/onDuty.jsp");
		//襄阳市公安局，需要加入当前时间段周数
		Date datetime = new Date();
		int weekdays = datetime.getDay();
		mv.addObject("weekdays",weekdays);
		
		return mv;
	}
	
	/**
	 * 论坛
	 * @param news
	 * @return
	 */
	@RequestMapping("/forum")
	public ModelAndView forums(News news) {
		ModelAndView mv = new ModelAndView("/forum/forumList.jsp");
		
		//襄阳市公安局，需要加入当前时间段周数
		Date datetime = new Date();
		int weekdays = datetime.getDay();
		mv.addObject("weekdays",weekdays);
		return mv;
	}
}
